﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Spider.Core;
using System.Reflection;
using Spider.Entity;
using Spider.Spider;

namespace Spider.Core
{
    public class SpiderEngin
    {
        public Dictionary<string, string> uris;

        private Main _mainForm;
        public Main MainForm
        {
            set { _mainForm = value; }
        }

        public void DoSpider()
        {
            ConfigManager cm = new ConfigManager();
            var config = cm.GetUriConfig();

            foreach (var item in config)
            {
                try
                {
                    Type t = Type.GetType(item.Key.Spider);
                    SpiderBase spider = (SpiderBase)Activator.CreateInstance(t);
                    spider.Config = item.Value;
                    spider.SiteName = item.Key.SiteName;
                    spider.Config = item.Value;
                    spider.SpiderCompleted += new SpiderCompletedEventHandler(spider_SpiderCompleted);
                    spider.Run();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        void spider_SpiderCompleted(object sender, SpiderEventArgs e)
        {
            uris = e.Uris;
            var result = uris.Distinct().OrderByDescending(p => p.Key.ToString());

      
            _mainForm.lbxUris.Items.AddRange(result.Select(p => p.Key).ToArray());
           // _mainForm.lbxUris.Items.AddRange(result.Select(p => p.Value).ToArray());
            ShowMessage(e.SiteName, uris.Count, result.Count());
        }

        private void ShowMessage(string siteName, int i, int j)
        {
            _mainForm.lbxMessage.Items.Add(
                string.Format("{0}： 共“{1}”条Uri，有效Uri“{2}”条。", siteName, i, j));
        }
    }
}
